import { defineStore } from "pinia";
import { ref, computed } from "vue";
import { useUserStore } from "../index";
import { cartAddAPI, cartListAPI, cartDeleteAPI } from "@/api/cart";
export const useCartStore = defineStore('cart', () => {
  // 定义购物车列表
  const cartList = ref([])
  const userStore = useUserStore()
  const token = computed(() => userStore.userInfo.token)
  // 获取购物车列表
  const updataCarlist = async () => {
    const res = await cartListAPI()
    cartList.value = res.result
  }
  // 添加购物车列表
  const addCart = async (cart) => {
    const { skuId, count } = cart
    if (token.value) {
      // 走接口
      console.log(skuId, count)
      await cartAddAPI({ skuId, count })
      // 获取购物车列表
      updataCarlist()
    } else {
      // 走本地
      // console.log(cart)
      const item = cartList.value.find(item => item.skuId === cart.skuId)
      if (item) {
        // 如果有就数量加传过来的数量
        item.count += cart.count
      } else {
        cartList.value.push(cart)
      }
    }

  }
  // 删除购物车列表
  const delCart = async (skuId) => {
    if (token.value) {
      console.log(skuId)
      await cartDeleteAPI([skuId])
      updataCarlist()
    } else {
      // 思路：
      // 1. 找到要删除项的下标值 - splice
      const idx = cartList.value.findIndex(item => item.skuId === skuId)
      cartList.value.splice(idx, 1)
      // 2. 使用数组的过滤方法 - filter
      // cartList.value = artList.value.filter(item => item.skuId !== skuId)
    }

  }
  // 清楚购物车
  const clearCart = () => {
    cartList.value = []
  }
  // 商品总数
  const totalCount = computed(() => {
    return cartList.value.reduce((sum, item) => {
      return sum += item.count
    }, 0)
  })
  // 商品总价
  const totalPirce = computed(() => {
    return cartList.value.reduce((sum, item) => {
      return sum += item.count * item.price
    }, 0)
  },)
  // 单选功能
  const singleCheck = (skuId, selected) => {
    // 找到要选择的项
    const item = cartList.value.find(item => item.skuId === skuId)
    item.selected = selected
  }
  // 全选
  const allCheck = computed(() => {
    return cartList.value.every(item => item.selected)
  })
  // 全选功能
  const allCheckChange = (selected) => {
    cartList.value.forEach(item => item.selected = selected)
  }

  // 选出选中的商品的总数
  const isCheckedCount = computed(() => {
    return cartList.value.filter(item => item.selected === true).reduce((sum, item) => {
      return sum + item.count
    }, 0)
  })
  // 选中商品的总价
  const isCheckedPrice = computed(() => {
    return cartList.value.filter(item => item.selected === true).reduce((sum, item) => {
      return sum + item.price * item.count
    }, 0)
  })
  return {
    cartList,
    addCart,
    delCart,
    totalCount,
    totalPirce,
    singleCheck,
    allCheck,
    allCheckChange,
    isCheckedCount,
    isCheckedPrice,
    clearCart,
    updataCarlist
  }
}, {
  persist: true
})
